<?php
/**
 * CloudProduct.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/27- 11:16 上午
 */

namespace common\services;

use common\dao\ComProductsDetailDao;
use common\exception\ServicesException;
use common\models\com\ComProductsSkus;
use common\dao\ComProductSkusDao;
use Yii;
use common\dao\ComProductsDao;
use yii\db\Exception;

class CloudProduct
{

    /**
     * 写入云商品库
     * @param array $products
     * @param array $details
     * @param array $skus
     * @return \common\models\com\ComProducts
     * @throws ServicesException
     * @throws \common\exception\ValidatorException
     */
    public function addProduct(array $products,array $details, array $skus)
    {

        /**
         * 增加事务，防止唯一性异常等情况
         */
//        $transaction=Yii::$app->db->beginTransaction();
        try {
            /**
             * 写入主表
             */
            $productInfo = (new ComProductsDao())->saveData($products);
            $details = array_merge(['product_id'=>$productInfo->id],$details);
            /**
             * 写入详细表
             */
            (new ComProductsDetailDao())->saveData($details);


            /**
             * 新增完后将云商品信息同步到es中
             */
//            $transaction->commit();
            /**
             * 写入sku表,判断sku是否存在，不存在不需要对sku表做操作
             */
            if(count($skus))
            {
                foreach($skus as $k => $sku)
                {
                    $skus[$k]['product_id'] = $productInfo->id;
                    $skus[$k]['uid'] = $productInfo->uid;
                    $skus[$k]['mall_id'] = $productInfo->mall_id;
                }
                $fields = array_keys($skus[0]);
                ComProductsSkus::deleteAll(['product_id'=>$productInfo->id]);
                Yii::$app->db->createCommand()->batchInsert(ComProductsSkus::tableName(),$fields,$skus)->execute();
//                (new ComProductSkusDao())->updateBatch($productInfo->id,$skus);
            }
//            $transaction->commit();
//            (new EsCloudProduct())->syncProduct($productInfo->id);
            return $productInfo;
        }catch (Exception $e)
        {
//            $transaction->rollBack();
            throw new ServicesException($e->getMessage());
        }

    }



}
